//
//  GameScene.m
//  iFly
//
//  Created by User-10 on 11/26/14.
//  Copyright (c) 2014 TeamDifferent. All rights reserved.
//

#import "GameScene.h"
#import "Constants.h"
#import "CharacterNode.h"
#import "EnemyFactory.h"
#import "EnemyNode.h"
#import "EnemyCharacterNode.h"

#import "FMMParallaxNode.h"
#import "PauseButton.h"
#import "FireButtonNode.h"
#import "ShieldButtonNode.h"

#import "ProjectileFactory.h"
#import "ProjectileNode.h"

#import "BonusFactory.h"
#import "BonusNode.h"

#import "Joystick.h"

#import "ContactHandler.h"
#import "SoundHandler.h"

@interface GameScene ()


@property NSTimeInterval lastUpdatedTime;
@property NSTimeInterval deltaTime;
@property NSTimeInterval start;
@property NSTimeInterval lastCoinAdded;
@property NSTimeInterval lastMissileAdded;
@property NSTimer* levelTimer;

@end
@implementation GameScene {
    CharacterNode* character;
    PauseButton* pauseButton;
    Joystick* joystick;
    SKLabelNode* scoreLabelNode;
    EnemyCharacterNode* enemyCharacter;
    
    float scaleCoef;
    
    FMMParallaxNode *_parallaxNodeBackgrounds;
    FMMParallaxNode *_parallaxSpaceDust;
    FMMParallaxNode *_parallaxMoon;
    FireButtonNode *fireButton;
    ShieldButtonNode *shieldButton;
    SKSpriteNode* background;
    NSInteger levelRemainingTime;
}


-(id)initWithSize:(CGSize)size {
    if(self = [super initWithSize:size]){
       
        scaleCoef= size.height/sceneScaling;
        
        //playing background music
        [[SoundHandler sharedSoundPlayer] playBackgroundMusicWithURL:@"IronManSong" andExtension:@"mp3"];
        
        self.backgroundColor = [SKColor blackColor];
        levelRemainingTime=30;
        levelRemainingTime=kLevelTime;
        
#pragma mark - Game backgrounds
        NSArray *parallaxBackgroundNames = @[ @"bg_galaxy1.png",
                                             @"bg_spacialanomaly.png", @"bg_pink_galaxy.png"];
        CGSize planetSizes = CGSizeMake(200.0, 200.0);
        _parallaxNodeBackgrounds = [[FMMParallaxNode alloc] initWithBackgrounds:parallaxBackgroundNames
                                                                           size:planetSizes
                                                           pointsPerSecondSpeed:10.0];
        _parallaxNodeBackgrounds.position = CGPointMake(size.width/2.0, size.height/2.0);
        [_parallaxNodeBackgrounds randomizeNodesPositions];
        [self addChild:_parallaxNodeBackgrounds];
        
        NSArray* parallaxOne = @[@"bg_half-moon.png"];
        CGSize moonSize = CGSizeMake(100.0, 100.0);
        _parallaxMoon = [[FMMParallaxNode alloc]initWithBackgrounds:parallaxOne size:moonSize pointsPerSecondSpeed:100.0];
        _parallaxMoon.position = CGPointMake(moonPosition, self.size.height/1.35);
        [self addChild:_parallaxMoon];
        
        //Bring on the space dust
        NSArray *parallaxBackground2Names = @[@"bg_front_spacedust.png",@"bg_front_spacedust.png"];
        _parallaxSpaceDust = [[FMMParallaxNode alloc] initWithBackgrounds:parallaxBackground2Names
                                                                     size:size pointsPerSecondSpeed:25.0];
        _parallaxSpaceDust.position = CGPointMake(0, 0);
        [self addChild:_parallaxSpaceDust];
        
        pauseButton=[PauseButton pauseButtonWithPosition:CGPointMake(100, 100) inScene:self];
        [self addChild:pauseButton];
        pauseButton.name=@"pause";

        [[UIApplication sharedApplication] delegate];
        [[NSNotificationCenter defaultCenter] addObserver:pauseButton selector:@selector(handlePause) name:UIApplicationWillResignActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:pauseButton selector:@selector(handlePause) name:UIApplicationDidBecomeActiveNotification object:nil];


        self.physicsWorld.contactDelegate = self;
        //level timer starting in the initializer
        self.levelTimer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(ending:) userInfo:nil repeats:YES];
        
#pragma mark - Initializing delay start of objects
        _start = 3;
        _lastMissileAdded = _start; //initializing first missile to start after 3 seconds
        _lastCoinAdded = _start; //initializing first coin to start after 3 seconds
    }
    return self;
}


-(void)didMoveToView:(SKView *)view {
    
    //adding character
    character = [CharacterNode characterWithPosition:CGPointMake(characterXPosition, self.frame.size.height/2) inScene:self];
    [character setScale:scaleCoef];
    [self addChild:character];
    
    //adding joystick
    joystick = [Joystick joystick];
    [self addChild:joystick];
    joystick.position = CGPointMake(self.scene.frame.origin.x+joystickOffset*scaleCoef, self.scene.frame.origin.y+joystickOffset*scaleCoef);
    joystick.name = @"joystick";
    [joystick setScale:scaleCoef*joystickScalling];
    
    fireButton = [FireButtonNode fireButtonOnPosition:CGPointMake(self.scene.size.width-fireButtonOffset*scaleCoef, fireButtonOffset*scaleCoef) inScene:self];
    [fireButton setScale:scaleCoef*fireButtonScaling];
    [self addChild:fireButton];
    //adding healthBar
    [self addHealthBar];
    shieldButton = [ShieldButtonNode shieldButtonOnPosition:CGPointMake(self.scene.size.width-fireButtonOffset*scaleCoef - fireButton.size.width - shieldButtonOffset*scaleCoef, fireButtonOffset*scaleCoef) inScene:self];
    [shieldButton setScale:scaleCoef*fireButtonScaling ];
    [self addChild:shieldButton];
    scoreLabelNode=[ Constants createLabelWithFont:labelFontName text:@"Score: 0" fontColor:[UIColor whiteColor] fontSize:25];
    scoreLabelNode.position=CGPointMake(self.scene.size.width/2,self.scene.size.height - buttonsOffset);
    scoreLabelNode.name=@"score";
    [self addChild:scoreLabelNode];
}


-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch* touch= [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode* touchedNode=[self nodeAtPoint:location];
    
    if (touchedNode == pauseButton) {
    
        if (pauseButton.isGamePaused == NO) {
            [[SoundHandler sharedSoundPlayer] pauseBackgroundMusic];
            [pauseButton handlePause];
        }
        else {
            [[SoundHandler sharedSoundPlayer] resumeBackgroundMusic];
            [pauseButton handleUnPause];
        }
    }
    SKNode* currentNode = [self nodeAtPoint:location];
        
    if ([currentNode.name  isEqual: @"fire"]) {
        [fireButton fire];
        return;
    }
    
    if([currentNode.name isEqual:@"shield"]){
        [shieldButton activateShield];
    }
    
}

//detecting contact between nodes;
- (void)didBeginContact:(SKPhysicsContact *)contact {
    SKPhysicsBody *firstBody, *secondBody;
    
    if (contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask) {
        firstBody = contact.bodyA;
        secondBody = contact.bodyB;
    }
    else {
        firstBody = contact.bodyB;
        secondBody = contact.bodyA;
    }
    [ContactHandler contactBetweenNodeA:(SKSpriteNode*)firstBody.node andNodeB:(SKSpriteNode*)secondBody.node];
}
//adding missiles
-(void)addEnemy {
    EnemyNode* missile = [EnemyFactory createEnemyWithType:EnemyTypeMissile inScene:self];
    [self addChild:missile];
    [missile setScale:scaleCoef/missileScaling];
    [missile moveToPosition:character.position];
}

//adding healthBar indicator
-(void) addHealthBar {
    SKSpriteNode* healthBar=[SKSpriteNode spriteNodeWithImageNamed:@"HealthBar3"];
    [healthBar setScale:scaleCoef/2];
    healthBar.position=CGPointMake(buttonsOffset + healthBar.size.width/2, self.scene.size.height - buttonsOffset*scaleCoef);
    healthBar.name=@"healthBar";
    healthBar.zPosition=1;
    [self addChild:healthBar];
}

-(void)addCoin {
    //initializing coin
    BonusNode* coin = [BonusFactory createBonusWithType:BonusTypeCoin inScene:self];
    if (coin) {
        SKAction* rotate= [SKAction rotateByAngle:M_PI duration:1.0];
        SKAction* repeatedRotation=[SKAction repeatActionForever:rotate];
        [coin runAction:repeatedRotation];
        [coin setScale:scaleCoef/coinScaling];

        [self addChild:coin];
    }
}

-(void) ending:(NSTimer*) timer {
    //not used for now
    if (levelRemainingTime == 0) {
        [character flyToTheBossScene];

    [timer invalidate];
    }
    else {
        if (!self.isPaused) {
        levelRemainingTime--;
        }
    }
   // timer
}

-(void)update:(CFTimeInterval)currentTime {
    //if game is paused do not update
    [character setScale:scaleCoef];


    if (self.paused) {
        return;
    }
    if (self.lastUpdatedTime) {
        self.deltaTime=currentTime - self.lastUpdatedTime;
    }
    else {
        self.deltaTime =0;
    }
    self.lastUpdatedTime=currentTime;
    
    if (self.start > 0) {
        //counting down the start of the missiles and coins for about 2 seconds
        self.start = self.start - self.deltaTime;
    }
    else {
        self.start = 0;
    }
    
    if (currentTime - self.lastCoinAdded > 0.5){
        if(self.lastCoinAdded > 1){
            self.lastCoinAdded = self.start;
        }
        else {
            self.lastCoinAdded = currentTime + 0.5;
            [self addCoin];
        }
    }
    
    if (currentTime - self.lastMissileAdded > 1){
        if (self.lastMissileAdded > 1){
            self.lastMissileAdded = self.start;
        }
        else {
            self.lastMissileAdded = currentTime + 1;
            [self addEnemy];
        }
    }
    //Update background (parallax) position
    [_parallaxSpaceDust update:currentTime];
    [_parallaxNodeBackgrounds update:currentTime];
    pauseButton.isParalaxPaused = NO;
}

@end
